package com.mobi.cacti.ns.view;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.ProgressBar;

import com.mobi.cacti.R;
import com.mobi.cacti.rabbit.response.Cache;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class NewsPromotionsDetailActivity extends Fragment {

	private WebView webView;
	private ProgressBar webViewProgressBar;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Bundle bundle = this.getArguments();
		String link = bundle.getString("link");

		View v = LayoutInflater.from(getActivity()).inflate(
				R.layout.newspromotionsdetail_layout, null);

		webViewProgressBar = (ProgressBar) v.findViewById(R.id.webviewprogressbar);
		
		webView = (WebView) v.findViewById(R.id.webview);
		setupWebView();

		try {
			// load the url
			webView.loadUrl(link);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return v;
	}

	private void setupWebView() {
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.getSettings().setBuiltInZoomControls(true);

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);

				webViewProgressBar.setVisibility(View.GONE);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				
				// display alert dialog
				Cache.showNoInternetAlertDialog(getActivity());
			}

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed(); // Ignore SSL certificate errors
			}
		});
	}

}
